#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Various top-level WSGI callables for handling a request to a tack install.


"""
from os import environ as osenv
from paste.cgitb_catcher import CgitbMiddleware

from tack.lib import not_found
from tack.lib.modtools import load_config, load_mods, load_urls
from tack.lib.dispatcher import dispatcher


def tack(environ, start_response):
    """ WSGI app to tack together a dispatcher, modules, and urls.

    """
    environ['tack.siteconfig'] = cfg = load_config(environ) 
    urls = load_urls(load_mods(cfg, environ))
    dispatch = dispatcher(urls, handle404=not_found)
    return dispatch(environ, start_response)


def main(environ, start_response):
    """ WSGI app wrapping the tack callable with an error catcher.

    """
    display = osenv.get('TACKDEBUG', '1') == '1'
    return CgitbMiddleware(tack, display=display)(environ, start_response)


## for mod_wsgi
application = main
